/*
 * Copyright (c) 2017 22420103@QQ.COM 版权所有
 *
 */

package com.lehe.controller.admin;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.lehe.dao.AdminUserDao;
import com.lehe.entry.*;
import com.lehe.service.impl.AdminUserService;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;
import org.jeecgframework.poi.excel.ExcelExportUtil;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.lehe.common.utils.StringUtil;
import com.lehe.dao.PayRecordDao;
import com.lehe.dao.UserManagerDao;
import com.lehe.service.impl.AdminFeeReportService;

/**
 * 类的相关描述
 *
 * @author 王丹
 * @since 2017-03-17
 */
@Controller
@RequestMapping("admin/excelExport")
public class ExcelExportController extends BaseAdminController{

    protected static final String HSSF         = ".xls";
    protected static final String XSSF         = ".xlsx";

    @Autowired
    AdminFeeReportService adminFeeReportService;
    @Autowired
    PayRecordDao payRecordDao;
    @Autowired
    UserManagerDao userManagerDao;
    @Autowired
	AdminUserDao adminUserDao;
	@Autowired
	AdminUserService adminUserService;


    @RequestMapping("dayFeeExcel")
    public void dayFeeExcel(SqlParameterDto sqlParameterDto, HttpServletRequest request, HttpServletResponse response) throws Exception{
        List<FeeReportDto> list = adminFeeReportService.queryDayFeeReport(sqlParameterDto);
        //导出Excel配置
        Workbook workbook = ExcelExportUtil.exportExcel(
                new ExportParams(sqlParameterDto.getStartDate() + "至" + sqlParameterDto.getEndDate() + "充值日报表","充值日报表"),
                FeeReportDto.class, list);
        String fileName = getFileName("充值日报表", request, workbook);
        response.setHeader("content-Type", "application/vnd.ms-excel");
        response.setHeader("content-disposition", "attachment;filename=" + fileName);
        workbook.write(response.getOutputStream());
    }

    @RequestMapping("monthFeeExcel")
    public void monthFeeExcel(SqlParameterDto sqlParameterDto, HttpServletRequest request, HttpServletResponse response) throws Exception{
        List<FeeReportDto> list = adminFeeReportService.queryMonthFeeReport(sqlParameterDto);
        //导出Excel配置
        Workbook workbook = ExcelExportUtil.exportExcel(
                new ExportParams(sqlParameterDto.getStartDate() + "至" + sqlParameterDto.getEndDate() + "充值日报表","充值月报表"),
                FeeReportDto.class, list);
        String fileName = getFileName("充值月报表", request, workbook);
        response.setHeader("content-Type", "application/vnd.ms-excel");
        response.setHeader("content-disposition", "attachment;filename=" + fileName);
        workbook.write(response.getOutputStream());
    }
    
    @RequestMapping("userInfoExport")
    public void userInfoExport(Long userId,Long agentId,String sd,String ed,Integer type,
    		HttpServletRequest request, HttpServletResponse response) throws Exception{
    	List result = null;
    	if(type.equals(1)){
    		result = payRecordDao.queryUserPayDetail(userId,sd,ed,null,null);
    	}else if(type.equals(2)){
    		result = payRecordDao.queryUserPlayerPayDetail(agentId,sd,ed,null,null);
    	}else if(type.equals(3)){
    		result = payRecordDao.queryUserAngentPayDetail(agentId,sd,ed,null,null);
    		//上级ID没有查询出来，再这里填充进去
    		for(Object o : result){
    			UserPayDto dto = (UserPayDto)o;
    			dto.setGroupId(userId);
    		}
    	}
    	Class target = null;
    	if(result.isEmpty()){
    		result.add(new UserPayDto());
    		target = UserPayDto.class;
    	}else{
    		target = result.get(0).getClass();
    	}
    	Workbook workbook = ExcelExportUtil.exportExcel(
                new ExportParams(sd + "至" + ed + "充值统计","充值统计"),
                target, result);
        String fileName = getFileName("充值统计", request, workbook);
        response.setHeader("content-Type", "application/vnd.ms-excel");
        response.setHeader("content-disposition", "attachment;filename=" + fileName);
        workbook.write(response.getOutputStream());
    }
    
    @RequestMapping("scoreExport")
    public void scoreExport(String userId,Long agentId,String sd,String ed,Integer type,
    		HttpServletRequest request, HttpServletResponse response) throws Exception{
    	List result = null;
		List<Long> ids = null;
		if(StringUtil.isBlank(userId)){
			ids = this.getGameUserIds();
		}else {
			ids = getUserIdsByAdmin(userId);
		}
    	if(type.equals(1)){
    		result = payRecordDao.queryUsersPayDetail(ids,sd,ed,null,null);
    	}else if(type.equals(2)){
			List<PlayerInfoDto> tmp = userManagerDao.queryUserPlayer(null,sd,ed,ids,null,null);
    		
    		result = new ArrayList<ExcelPlayerInfoDto>();
    		for(PlayerInfoDto t : tmp){
    			ExcelPlayerInfoDto e = new ExcelPlayerInfoDto();
    			result.add(e);
    			e.setGoldCoinCount(t.getGoldCoinCount());
    			e.setLoginTime(t.getLoginTime());
    			e.setTotalFee(t.getTotalFee());
    			e.setNickName(t.getNickName());
    			e.setUserId(t.getUserId());
    			e.setYqr(t.getGroupName()+"("+t.getGroupId()+")");
    		}
    	}else if(type.equals(3)){
    		//agentId为空，则查询关联的用户记录
    		if(agentId == null){

				result = userManagerDao.queryUserAgentByIds(null,sd,ed, ids,null,null, null,null);
    		}else{
    			//这个查询是要用agentId查询
    			result = userManagerDao.queryUserAgent(null,agentId,sd,ed,null,null,null,null);
    		}
    	}else if(type.equals(4)){
			result = userManagerDao.queryUserGold(userId,sd,ed,null,null,null);
		}
    	Class target = null;
    	if(result.isEmpty()){
    		result.add(new UserPayDto());
    		target = UserPayDto.class;
    	}else{
    		target = result.get(0).getClass();
    	}
    	Workbook workbook = ExcelExportUtil.exportExcel(
                new ExportParams(sd + "至" + ed + "充值统计","充值统计"),
                target, result);
        String fileName = getFileName("充值统计", request, workbook);
        response.setHeader("content-Type", "application/vnd.ms-excel");
        response.setHeader("content-disposition", "attachment;filename=" + fileName);
        workbook.write(response.getOutputStream());
    }

    private String getFileName(String fileName, HttpServletRequest request, Workbook workbook) throws Exception {
        if(StringUtil.isBlank(fileName)){
            fileName = "defaultExcel";
        }
        if (workbook instanceof HSSFWorkbook) {
            fileName += HSSF;
        } else {
            fileName += XSSF;
        }
        if (StringUtil.isIE(request)) {
            fileName = java.net.URLEncoder.encode(fileName, "UTF8");
        } else {
            fileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
        }
        return fileName;
    }

	private List<Long> getUserIdsByAdmin(String seachStr){
		List<Long> ret = new ArrayList<>();
		AdminUserDto adminUserDto = adminUserService.queryByIdOrAccount(seachStr);
		if (null == adminUserDto) {
			return ret;
		}
		if(StringUtil.isNotBlank(adminUserDto.getUserIds())){
			ret = Arrays.stream(adminUserDto.getUserIds().split(",")).map(Long::parseLong).collect(Collectors.toList());
		}
		return ret;
	}
}
